#ifndef DATA_REPO
#define DATA_REPO
#include "Message.hpp"
//#include "Config.hpp"
#include <boost/shared_ptr.hpp>
#include "pthread.h"
#include <map>
//TODO, Data repo will cinsider data as too old ( and hence as not available  ) if it is more than 5 seconds old
//This is actually already implemented, I just
const double c_Old = 10 ;
class DataBean
{

public:

	typedef boost::shared_ptr<DataBean> BeanPointer;
	DataType	m_Type;
	std::string m_value;
	time_t		m_TimeStamp;

};

class DataRepo{

	typedef std::map< DataType, DataBean::BeanPointer > DataMap;
	DataMap m_DataMap;

	//Locking.
	pthread_mutex_t MapMutex;

public:
	time_t m_LastDataUpdate;

	DataRepo()
	{
		pthread_mutex_init( &MapMutex , NULL );
	}

	~DataRepo()
	{
		pthread_mutex_destroy( &MapMutex );
	}

	bool GetData( DataType Type, time_t& timeStamp, std::string& value )
	{

		pthread_mutex_lock( &MapMutex );
		DataMap::iterator it;
		it = m_DataMap.find( Type );
		time_t NOW( NULL );



		bool available = ( ( it == m_DataMap.end() ) ? false : true );
		bool toOold;

		if( available )
		{
			double timediff = difftime( NOW, it->second->m_TimeStamp );
			toOold			= ( timediff > c_Old );

			timeStamp	= it->second->m_TimeStamp;
			value		= it->second->m_value;
		}

		pthread_mutex_unlock( &MapMutex );
		return ( available && !toOold );
	}
	//Returns "True" if the data is new to the server.
	bool SaveData( DataType Type, time_t fillTime, std::string val )
	{
		pthread_mutex_lock( &MapMutex );
		DataMap::iterator it;
		it = m_DataMap.find( Type );
		bool isNew = false;

		if( it != m_DataMap.end() )
		{
			m_DataMap[ Type ]->m_TimeStamp	= time( NULL );
			m_DataMap[ Type ]->m_value		= val ;
			isNew 							= false;
		}
		else
		{
			DataBean::BeanPointer newdata( new DataBean );
			newdata->m_TimeStamp	= time( NULL );
			newdata->m_value		= val;
			m_DataMap[ Type ]		= newdata;
			isNew 					= true ;
		}
		m_LastDataUpdate = m_DataMap[ Type ]->m_TimeStamp;
		pthread_mutex_unlock( &MapMutex );
		return isNew;
	}


};


#endif
